package ws

import "sync"

type IClientsMgr interface {
	AddClient(c *Client)
	DeleteClient(c *Client)

	Clients() []*Client //return all clients
	Conns() int64       //return clients num
}

func NewClientsMgr() *ClientsMgr {
	return &ClientsMgr{
		clients: make(map[*Client]bool, 128),
	}
}

//ClientsMgr 联机客户端管理
type ClientsMgr struct {
	clients map[*Client]bool

	//总连接数量
	conn int64

	mu sync.RWMutex
}

func (w *ClientsMgr) AddClient(c *Client) {
	w.mu.Lock()
	if _, exist := w.clients[c]; !exist {
		w.clients[c] = true
		w.conn += int64(1)
	}
	w.mu.Unlock()
}

func (w *ClientsMgr) DeleteClient(c *Client) {
	w.mu.Lock()
	if _, exist := w.clients[c]; exist {
		delete(w.clients, c)
		w.conn -= int64(1)
	}
	w.mu.Unlock()
}

func (w *ClientsMgr) Clients() []*Client {
	clients := make([]*Client, 0)

	w.mu.RLock()
	for c := range w.clients {
		clients = append(clients, c)
	}
	w.mu.RUnlock()

	return clients
}

func (w *ClientsMgr) Conns() int64 {
	return w.conn
}
